<template>
  <div >
    <van-nav-bar
      title="文件差分"
    />
    <div class="container">
      <van-uploader accept="application/vnd.android.package-archive" class="mtop10" :after-read="onOldFileSeleted">
        <van-card
          title="原始包"
          :desc="originFile?originFile.file.name:'未选择'"
          :price="originFile?getFilesize(originFile.file.size):''"
          :thumb="icon"
          currency=""
        />
      </van-uploader>
      <van-uploader accept="application/vnd.android.package-archive" class="mtop10" :after-read="onNewFileSelected">
        <van-card
          title="更新包"
          :desc="newFile?newFile.file.name:'未选择'"
          :price="newFile?getFilesize(newFile.file.size):''"
          :thumb="icon"
          currency=""
        />
      </van-uploader>
      <van-card
          v-if="diffUrl"
          class="mtop10"
          title="查分包"
          :desc="diffUrl"
          :thumb="icon"
          currency=""
        >
        <div slot="footer" class="row">
          <van-button @click="checkFile" size="mini">校验</van-button>
          <van-button @click="uploadPatch" size="mini">上传</van-button>
        </div>
      </van-card>
      <van-button  :disabled="!submitEnable" class="mtop10" size="large" type="primary" :loading="loading" @click="processDiff">生成差分包</van-button>
    </div>
  </div>
</template>
<script>
const iconUrl = require('../assets/icon_apk.png')
import { Toast } from 'vant';
export default {
  name: 'upload',
  data() {
    return {
      icon: iconUrl,
      diffUrl: '',
      originFile:null,
      newFile:null,
      loading: false,
    }
  },
  computed:{
    submitEnable(){
      return this.originFile!=null && this.newFile !=null;
    }
  },
  methods:{
    getBlob(buffer, format) {
      try {
        return new window.Blob(buffer, { type: format })
      } catch (e) {
        const bb = new (window.BlobBuilder ||
          window.WebKitBlobBuilder ||
          window.MSBlobBuilder)()
        buffer.forEach(buf => {
          bb.append(buf)
        })
        return bb.getBlob(format)
      }
    },
    getFilesize(size){
      return Math.floor(size/1024)+'K'
    },
    onOldFileSeleted(file) {
      console.log(file)
      this.originFile = file
    },onNewFileSelected(file) {
      console.log(file)
      this.newFile = file
    },
    async processDiff() {
      this.loading = true;
      const imageTasks = []
      imageTasks.push(this.uploadFile(this.originFile));
      imageTasks.push(this.uploadFile(this.newFile));
      const resp = await Promise.all(imageTasks)
      const data = {
        originFile: this.originFile.uploadResponse.data.data,
        newFile :this.newFile.uploadResponse.data.data
      }
      this.$axios.post('/api/diff',data).then(res=>{
          this.loading = false;
          if(res.data.result == 'success') {
            this.diffUrl = res.data.data;
          }else {
            console.log(res.data.msg || '上传失败')
          }
      });

    },
    uploadPatch() {
      this.$router.push({path:'manage', query: {
        fromFile: this.originFile.file.name,
        toFile: this.newFile.file.name,
        patchFile: this.diffUrl,
      }});
    },
    checkFile() {
      const data = {
        originFile: this.originFile.uploadResponse.data.data,
        patchFile :this.diffUrl,
        newFile :this.newFile.uploadResponse.data.data
      }
      this.$axios.post('/api/patch',data).then(res=>{
          this.loading = false;
          if(res.data.result == 'success') {
            Toast('校验成功');
          }else {
            Toast(res.data.msg || '上传失败')
          }
      });
    },
    uploadFile(file) {
      return new Promise(reslove => {
        const { type } = file.file
        const text = window.atob(file.content.split(',')[1])
        const buffer = new Uint8Array(text.length)
        for (let i = 0; i < text.length; i++) {
          buffer[i] = text.charCodeAt(i)
        }
        const blob = this.getBlob([buffer], type)
        const param = new window.FormData()
        param.append('file', blob, file.file.name)
        const config = {
          headers: { 'Content-Type': 'multipart/form-data' }
        }
        this.$axios.post('/api/upload', param, config).then(
          response => {
            file.uploadResponse = response;
            reslove(response)
          },
          () => {
            reslove({})
          }
        )
      })
    },
  }
}
</script>

<style scoped>
  .page {

  }
  .container {
    flex:1;
    display: flex;
    flex-direction: column;
    align-items: stretch;
    padding-left: 12px;
    padding-right: 12px;
  }
  .mtop10 {
    margin-top: 10px;
  }
  .row {
    flex-direction: row;
  }
</style>
